package it.xiuxian.swindle.fragment

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.text.Editable
import android.util.Log
import android.view.View
import android.widget.CheckBox
import android.widget.CompoundButton
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.github.yoojia.inputs.AndroidNextInputs
import com.lljjcoder.Interface.OnCityItemClickListener
import com.lljjcoder.bean.DistrictBean
import com.lljjcoder.bean.ProvinceBean
import com.lljjcoder.style.cityjd.JDCityConfig
import com.lljjcoder.style.cityjd.JDCityPicker
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.tbruyelle.rxpermissions2.RxPermissions
import it.xiuxian.lib.base.ArouterAddress
import it.xiuxian.lib.base.BaseFragment
import it.xiuxian.lib.utils.*
import it.xiuxian.lib.utils.adapter.SlimAdapter
import it.xiuxian.lib.utils.adapter.SlimInjector
import it.xiuxian.lib.utils.adapter.injector.IViewInjector
import it.xiuxian.swindle.R
import it.xiuxian.swindle.bean.ImageBean
import it.xiuxian.swindle.bean.NewBaseBean
import it.xiuxian.swindle.bean.NewImageBean
import it.xiuxian.swindle.databinding.FragmentGongyiBinding
import it.xiuxian.swindle.presenter.GongYIFragmentPresenter
import org.json.JSONObject
import java.io.File


@Route(path = ArouterAddress.GONGYIFRAGMENT)
class GongYIFragment:BaseFragment<GongYIFragmentPresenter>(){
    lateinit var binding:FragmentGongyiBinding
    lateinit var adapter:SlimAdapter
    var cityPicker: JDCityPicker? = null
    var mWheelType = JDCityConfig.ShowType.PRO_CITY_DIS
   lateinit var inputs: AndroidNextInputs
   var address:String?=null

    private val jdCityConfig = JDCityConfig.Builder().build()
    override val layoutId: Int
        get() = R.layout.fragment_gongyi
    override val presenter: GongYIFragmentPresenter
        get() = GongYIFragmentPresenter()

    override fun isEmpty(textView: TextView?): Boolean{
        return false
    }

    override fun initView(){
        setTitle("上传公益照片")
      binding =   getViewDataBinding<FragmentGongyiBinding>()
        inputs = ToastNextInputs()
        inputs.clear()
        inputs.add(binding.etTitle, SchemeUtil.notEmpty(binding.etTitle))
        binding.image.setOnClickListener {
            selectPic()
        }
        cityPicker = JDCityPicker()
        jdCityConfig.showType = mWheelType
        //初始化数据
        cityPicker!!.init(requireActivity())
        //设置JD选择器样式位只显示省份和城市两级
        cityPicker!!.setConfig(jdCityConfig)
        cityPicker!!.setOnCityItemClickListener(object : OnCityItemClickListener(){
            override fun onSelected(
                province: ProvinceBean,
                city: com.lljjcoder.bean.CityBean,
                district: DistrictBean
            ) {
                var proData: String? = null
              /*  if (province != null) {
                   // provinceid = province.id
                    // proData = "name:  " + province.name + "   id:  " + province.id
                }
                var cituData: String? = null
                if (city != null) {
                  //  cityid = city.id
                    //  cituData = "name:  " + city.name + "   id:  " + city.id
                }
                var districtData: String? = null
                if (district != null) {
                   // areaid = district.id
                    //   districtData = "name:  " + district.name + "   id:  " + district.id
                }*/
                binding.tvAddress.text = if(city.name=="市辖区") province.name else city.name
                address = if(city.name=="市辖区") province.name else city.name

            }

            override fun onCancel(){}
        })
        binding.llAddress.setOnClickListener{
            showJD()
        }
        binding.tvDelete.setOnClickListener{
          var bb=  aa.toMutableList()
            Log.e("bb",bb.toString())
          for(i in aa){
              if(i.boolean){
                  bb.remove(i)
              }
          }
            Log.e("bb",bb.toList().toString())
            aa.clear()
            bean.isflag = false
            binding.tvDelete.visibility=View.INVISIBLE
           if(bb.toList().isNotEmpty()) {
               aa.addAll(bb.toList())
           }
            adapter.updateData(aa)
        }
        GridLayoutManager(requireActivity(),3).also { binding.rv.layoutManager = it }
        adapter = SlimAdapter.create().register<NewBaseBean>(R.layout.swindle_gongyi_item,
            object: SlimInjector<NewBaseBean>{
                override fun onInject(
                    data: NewBaseBean?,
                    injector: IViewInjector<out IViewInjector<*>>?
                ) {
                    val checkBox= injector!!.findViewById<CheckBox>(R.id.checkbox)
                    checkBox.isChecked = data!!.boolean
                    if(bean.isflag){
                        checkBox.setOnCheckedChangeListener(object :CompoundButton.OnCheckedChangeListener{
                            override fun onCheckedChanged(
                                buttonView: CompoundButton?,
                                isChecked: Boolean
                            ) {
                                data.boolean = isChecked

                            }

                        })
                        checkBox.visibility = View.VISIBLE
                    }else{
                        checkBox.visibility = View.INVISIBLE
                    }
                    ImageUtil.setImage(data.img,injector.findViewById<ImageView>(R.id.imageview))


                }
            }).attachTo(binding.rv)
        ItemClickSupport.addTo(binding.rv).setOnItemLongClickListener(object :
            ItemClickSupport.OnItemLongClickListener {
            override fun onItemLongClicked(rv: RecyclerView?, position: Int, view: View?): Boolean {
                bean.isflag = true
                adapter.updateData(aa)
                Log.e("position",position.toString())
                binding.tvDelete.visibility = View.VISIBLE
               return false
            }

        })
        binding.tvSubmit.setOnClickListener{
           if(Utils.isFastClick()){
               if(inputs.test()){
                   val json1 = JSONObject()
                   var imag:String=""
                   if(aa.isNotEmpty()){
                       for(i in aa){
                           imag += "${i.img},"
                       }
                       json1.put("imgurl",imag.substring(0,imag.length-1))
                       json1.put("message",binding.etTitle.text.toString())
                       json1.put("address",binding.tvAddress.text.toString())
                       mPresenter!!.submit(json1)
                   }else{
                       ToastUtil.showShort("请先选图片")
                   }
               }
           }

        }
        binding.tvChongxuan.setOnClickListener{
            aa.clear()
            binding.tvDelete.visibility = View.INVISIBLE
            adapter.updateData(aa)
        }
    }
    private fun showJD(){
        cityPicker!!.showCityPicker()
    }
    @SuppressLint("CheckResult")
    fun selectPic(){
        RxPermissions(requireActivity())
            .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
            .subscribe(io.reactivex.functions.Consumer<Boolean> { granted: Boolean ->
                if (granted){
                    PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        /*.cropImageWideHigh(900,1080)
                        .isEnableCrop(true)
                        .cutOutQuality(100)
                        .isMultipleSkipCrop(true)
                        .showCropFrame(true)
                        .showCropGrid(true)*/
                        .previewImage(true)
                        .loadImageEngine(GlideEngine.createGlideEngine())
                        .isCamera(true)
                        .imageFormat(PictureMimeType.PNG_Q)
                        .maxSelectNum(9)
                        .isCompress(true)
                        .compressQuality(100)
                        .forResult(PictureConfig.CHOOSE_REQUEST)

                }
            })

    }
    private lateinit var filePath: String

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ): Unit {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK){
            when (requestCode){
                PictureConfig.CHOOSE_REQUEST ->{
                    val selectList = PictureSelector.obtainMultipleResult(data)
                    for( media in selectList){
                       // val media = selectList[0]
                        if (media.isCompressed){
                            filePath = media.compressPath
                        } else {
                            filePath = media.path
                        }
                        Log.e("PictureConfig","filepath路径:"+filePath)
                        mPresenter!!.onload(File(filePath))
                    }

                }
            }
        }
    }
    var aa = ArrayList<NewBaseBean>()
    lateinit var bean:NewImageBean
    fun updata(data: ImageBean){

        for((index,i) in data.imgurl.withIndex()){
            aa.add(NewBaseBean(i,false))
        }
         bean = NewImageBean(aa,false)
      //  aa.addAll(aa)
        adapter.updateData(aa)
        Log.e("aa",aa.toString())
    }

    fun update(msg: String){
        ToastUtil.showShort(msg)
        aa.clear()
       adapter.updateData(aa)
        binding.etTitle.text= Editable.Factory.getInstance().newEditable("")
        binding.tvAddress.text="郑州"
    }
}